package org.zjvis.datascience.common.util;

import java.io.*;

/**
 * @author AaronY
 * @version 1.0
 * @since 2022/7/19
 */
public class CommandUtil {

    /**
     * 默认输出字符集，设置成其它字符集中文会乱码
     */
    private static final String DEFAULT_CHARSET = "gb2312";

    public static String stream2Str(InputStream inputStream, String charset) throws IOException {
        try (
                ByteArrayOutputStream out = new ByteArrayOutputStream();
        ) {

            byte[] bytes = new byte[4096];
            int len = -1;
            while ((len = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }

            return out.toString(charset);

        }
    }

    /**
     * 执行系统命令
     *
     * @param command 命令
     * @return 命令执行完成输出内容
     * @throws IOException 执行失败时抛出异常，由调用者捕获处理
     * @throws InterruptedException 执行中断时抛出异常，由调用者捕获处理
     */
    public static String exec(String command, String [] params, String charset) {
        try{
            Process process = Runtime.getRuntime().exec(command, params);
            String outStr = stream2Str(process.getInputStream(), charset);
            String errStr = stream2Str(process.getErrorStream(), charset);
            int exitValue = process.waitFor(); // 退出值 0 为正常，其他为异常
            process.waitFor();

            if (exitValue == 0){
                return  outStr;
            }else {
                return errStr;
            }
        } catch (IOException | InterruptedException e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

    public static String exec(String[] command, String [] params, String charset) {
        try{
            Process process = Runtime.getRuntime().exec(command, params);
            String outStr = stream2Str(process.getInputStream(), charset);
            String errStr = stream2Str(process.getErrorStream(), charset);
            int exitValue = process.waitFor(); // 退出值 0 为正常，其他为异常
            process.waitFor();

            if (exitValue == 0){
                return  outStr;
            }else {
                return errStr;
            }
        } catch (IOException | InterruptedException e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

    /**
     * 执行系统命令
     *
     * @param command 命令
     * @return 命令执行完成输出内容
     * @throws IOException 执行失败时抛出异常，由调用者捕获处理
     * @throws InterruptedException 执行中断时抛出异常，由调用者捕获处理
     */
    public static String exec(String command, String[] params) {
        return exec(command, params, DEFAULT_CHARSET);
    }

    /**
     * 执行系统命令
     *
     * @param command 命令
     * @return 命令执行完成输出内容
     * @throws IOException 执行失败时抛出异常，由调用者捕获处理
     * @throws InterruptedException 执行中断时抛出异常，由调用者捕获处理
     */
    public static String exec(String command, String charset)  {
        return exec(command, new String[]{}, charset);
    }

    /**
     * 执行系统命令
     *
     * @param command 命令
     * @return 命令执行完成输出内容
     * @throws IOException 执行失败时抛出异常，由调用者捕获处理
     * @throws InterruptedException 执行中断时抛出异常，由调用者捕获处理
     */
    public static String exec(String command) {
        return exec(command, DEFAULT_CHARSET);
    }

    public static String exec(String[] command) {
        return exec(command, new String[]{}, DEFAULT_CHARSET);
    }


    public static void main(String[] args) {
        String [] commands = new String[]{
                "ls -al",
                "for ((i=0;i<1;i++))do echo ./csv_tmp/CSV-16589763973971632h6e68_$i.csv;done | xargs -i cat {} > ./csv_tmp/CSV-16589763973971632h6e68.csv",
                "shp2pgsql -s 3819 -W GBK -k ./gpdata/gis/1632-1658975740154-4081/1632.shp dataset.v_1632_1658975749495>./gpdata/gis/1632-1658975740154-4081/1632.sql"
        };
        for (String cmd: commands) {
            String result = CommandUtil.exec(cmd);
            System.out.println(cmd + " -> " + result);
        }
    }

}
